import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Commodity {
  String name;
  int stock;

  Commodity({required this.name, required this.stock});
}


class CommodityNotifier extends ChangeNotifier {


  Commodity? _commodity;

  Commodity? get commodity => _commodity;

  void setCommodity(Commodity commodity) {
    _commodity = commodity;
    notifyListeners(); // 通知 UI 更新
  }



  // Commodity _commodity;
  //
  // CommodityNotifier(this._commodity);

  // Commodity get commodity => _commodity;

  // void increaseStock() {
  //   _commodity.stock++;
  //   _commodity.name="123";
  //   notifyListeners(); // 通知 UI 更新
  // }
}


class CommodityPage extends StatelessWidget {
  final Commodity initialCommodity = Commodity(name: 'Sample Product', stock: 10);

  CommodityPage({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => CommodityNotifier(),
      child: CommodityDetails(),
    );
  }
}

class CommodityDetails extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 获取商品状态

    final notifier = context.watch<CommodityNotifier>();

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (notifier.commodity != null) ...[
            Text(
              '商品名称: ${notifier.commodity!.name}',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 10),
            Text(
              '库存数量: ${notifier.commodity!.stock}',
              style: TextStyle(fontSize: 20),
            ),
          ] else ...[
            Text(
              '商品未设置',
              style: TextStyle(fontSize: 20, color: Colors.red),
            ),
          ],
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {
              notifier.setCommodity(
                Commodity(name: 'Sample Product', stock: 10),
              );
              // 调用增加库存的方法
            },
            child: Text('增加库存'),
          ),
        ],
      ),
    );
  }
}

